import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { User, LoginRequest, RegisterRequest, USER_ROLES, RoleQueryResponse } from '@/types'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string>(localStorage.getItem('token') || '')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  // 登录
  const login = async (loginData: LoginRequest) => {
    try {
      console.log('开始登录，参数:', {
        loginName: loginData.username,
        pwd: loginData.password
      })
      
      // 1. 调用登录接口获取token
      const loginResponse = await request.post('/user/login', {
        loginName: loginData.username,
        pwd: loginData.password
      })
      
      console.log('登录响应:', loginResponse)
      
      const newToken = loginResponse.data as any
      token.value = newToken
      
      // 保存token到本地存储
      localStorage.setItem('token', newToken)
      
      // 2. 根据用户名查询用户角色
      console.log('查询用户角色，参数:', { userName: loginData.username })
      
      const roleResponse = await request.get('/user/getByUserName', {
        params: { userName: loginData.username }
      })
      
      console.log('角色查询响应:', roleResponse)
      
      // 从响应中正确提取用户角色
      const roleData = roleResponse 
      const userRole = roleData.data.userRole
      const nickname = roleData.data.userName
      const avatar = roleData.data.userAvatar
      const email = roleData.data.userEmail
      
        
      
      // 3. 构造用户信息
      user.value = {
        //id: 0, // 这里可能需要从其他地方获取
        username: loginData.username,
        role: userRole === USER_ROLES.ADMIN ? 'admin' : 'user',
        userRole: userRole,
        nickname: nickname,
        email: email,
        avatar:avatar
        
      } as User
      
      // 保存用户信息到本地存储
      localStorage.setItem('user', JSON.stringify(user.value))
      
      // 返回登录结果，包含token和用户角色
      return { 
        token: newToken, 
        userRole,
        user: user.value
      }
    } catch (error: any) {
      console.error('登录失败:', error)
      console.error('错误详情:', error.response?.data)
      
      // 清理可能的部分状态
      token.value = ''
      user.value = null
      localStorage.removeItem('token')
      
      throw error
    }
  }

  // 注册
  const register = async (registerData: RegisterRequest) => {
    try {
      const response = await request.post('/user/register', registerData)
      return response
    } catch (error) {
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = async (userData: Partial<User>) => {
    try {
      // 根据后端接口要求，需要传递userAccount字段
      const updateData = {
        userAccount: user.value?.username, // 用户名作为userAccount
        userName: userData.nickname,
        userEmail: userData.email,
        userAvatar: userData.avatar
      }
      
      console.log('更新用户信息，发送数据:', updateData)
      const response = await request.put('/user/update', updateData)
      console.log('更新用户信息响应:', response)
      
      // 检查响应状态
      if (response && response.data) {
        // 更新本地用户信息
        if (user.value) {
          user.value = { 
            ...user.value, 
            nickname: userData.nickname,
            email: userData.email,
            avatar: userData.avatar
          }
          // 更新本地存储
          localStorage.setItem('user', JSON.stringify(user.value))
        }
        return response
      } else {
        throw new Error(response?.data?.message || '更新失败')
      }
    } catch (error: any) {
      console.error('更新用户信息失败:', error)
      if (error.response?.data?.message) {
        throw new Error(error.response.data.message)
      }
      throw error
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      const response = await request.put('/user/password', {
        oldPassword,
        newPassword
      })
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value && !user.value) {
      // 尝试从本地存储恢复用户信息
      const savedUser = localStorage.getItem('user')
      if (savedUser) {
        try {
          user.value = JSON.parse(savedUser)
          console.log('从本地存储恢复用户信息成功')
          return
        } catch (parseError) {
          console.error('解析本地用户信息失败:', parseError)
          logout()
        }
      } else {
        // 如果没有本地存储的用户信息，清理状态
        console.log('没有找到本地用户信息，清理登录状态')
        logout()
      }
    }
  }

  // 获取最新用户列表
  const getLatestUsers = async (limit: number = 4) => {
    try {
      // 调用后端用户列表接口，获取所有用户
      const response = await request.get('/user/list', {
        params: {
          pageNum: 1,
          pageSize: 100 // 获取足够多的用户以便排序
        }
      }) as any
      
      if (response && response.data && response.data.data) {
        // 按注册时间排序，获取最新的用户
        const allUsers = response.data.data
        const sortedUsers = allUsers.sort((a: any, b: any) => {
          return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
        })
        
        // 返回最新的指定数量用户
        return sortedUsers.slice(0, limit)
      }
      
      return []
    } catch (error) {
      console.error('获取最新用户失败:', error)
      return []
    }
  }

  // 获取用户总数
  const getUserCount = async () => {
    try {
      const response = await request.get('/user/list', {
        params: {
          pageNum: 1,
          pageSize: 1
        }
      }) as any
      
      if (response && response.data && response.data.allRow !== undefined) {
        return response.data.allRow
      } else {
        return 0
      }
    } catch (error) {
      console.error('获取用户总数失败:', error)
      return 0
    }
  }

  // 根据用户ID获取用户信息
  const getUserById = async (userId: number) => {
    try {
      const response = await request.get(`/user/${userId}`) as any
      
      if (response && response.data) {
        return response.data
      } else {
        return null
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    isAdmin,
    login,
    register,
    updateUserInfo,
    changePassword,
    logout,
    initUserInfo,
    getLatestUsers,
    getUserCount,
    getUserById
  }
}) 